package vn.com.ltv.lo.common;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.json.JSONArray;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.Configuration;
import android.net.ConnectivityManager;
import android.os.Build;
import android.provider.Settings;
import android.util.DisplayMetrics;
import android.util.Patterns;
import android.view.Display;
import android.view.View;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.view.inputmethod.InputMethodManager;

public class ConfigsAndroid {

	/**
	 * Determine if the device is a tablet (i.e. it has a large screen).
	 * 
	 * @param context
	 *            The calling context.
	 */
	public final static int TAB_NORMAL = 0;
	public final static int TAB_LARGE = 1;
	public final static int TAB_SMALL = 2;
	public final static int TAB_XLARGE = 3;

	public final static int MDPI = DisplayMetrics.DENSITY_MEDIUM;
	public final static int HDPI = DisplayMetrics.DENSITY_HIGH;
	public final static int XDPI = DisplayMetrics.DENSITY_XHIGH;

	public static boolean isTablet(Context context) {
		return (context.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) >= Configuration.SCREENLAYOUT_SIZE_LARGE;
	}

	public static int getTabAndroid(Context context) {
		int idTab = 0;
		DisplayMetrics metrics = new DisplayMetrics();
		((Activity) context).getWindowManager().getDefaultDisplay()
				.getMetrics(metrics);
		int widthPixels = metrics.widthPixels;
		int heightPixels = metrics.heightPixels;

		float scaleFactor = metrics.density;
		float widthDp = widthPixels / scaleFactor;
		float heightDp = heightPixels / scaleFactor;
		float smallestWidth = Math.min(widthDp, heightDp);

		if (smallestWidth > 600) {
			idTab = TAB_LARGE;
		} else if (smallestWidth > 720) {
			idTab = TAB_XLARGE;
		} else {
			idTab = TAB_NORMAL;
		}
		return idTab;
	}

	public static int getDpiAndroid(Context context) {
		return ((Activity) context).getResources().getDisplayMetrics().densityDpi;
	}

	/**
	 * Get the current Android API level.
	 */
	public static int getSdkVersion() {
		return Build.VERSION.SDK_INT;
	}

	/**
	 * Get width screen device
	 */
	public static int getWidthMagic(Context context) {
		DisplayMetrics metrics = new DisplayMetrics();
		((Activity) context).getWindowManager().getDefaultDisplay()
				.getMetrics(metrics);
		return metrics.widthPixels;
	}

	/**
	 * Get the current version name level.
	 */
	public static String getVersionName(Context context) {
		try {
			PackageInfo packageInfo = context.getPackageManager()
					.getPackageInfo(context.getPackageName(), 0);
			return packageInfo.versionName;
		} catch (NameNotFoundException e) {
			// should never happen
			throw new RuntimeException("Could not get package name: " + e);
		}
	}
	
	public static float getWidthDp(Context context){
		Display display = ((Activity) context).getWindowManager().getDefaultDisplay();
	    DisplayMetrics outMetrics = new DisplayMetrics ();
	    display.getMetrics(outMetrics);

	    float density  = ((Activity) context).getResources().getDisplayMetrics().density;
	    float dpWidth  = outMetrics.widthPixels / density;
	    
	    return dpWidth;
	}

	/**
	 * Determine if the device is running API level 8 or higher.
	 */
	public static boolean isFroyo() {
		return getSdkVersion() >= Build.VERSION_CODES.FROYO;
	}

	/**
	 * Determine if the device is running API level 11 or higher.
	 */
	public static boolean isHoneycomb() {
		return getSdkVersion() >= Build.VERSION_CODES.HONEYCOMB;
	}

	/**
	 * Determine if the device is a HoneyComb tablet.
	 * 
	 * @param context
	 *            The calling context.
	 */
	public static boolean isHoneycombTablet(Context context) {
		return isHoneycomb() && isTablet(context);
	}

	/**
	 * Get deviceID of the device
	 * 
	 * @param context
	 *            The calling context.
	 * @return deviceID
	 */
	public static String deviceID(Context context) {
		return Settings.Secure.getString(context.getContentResolver(),
				Settings.Secure.ANDROID_ID);
	}

	/**
	 * Check connect Internet
	 * 
	 * @param ctx
	 *            The calling context.
	 * @return true if connect, false otherwise.
	 */
	public static boolean isNetworkAvailable(Context ctx) {

		ConnectivityManager connMgr = (ConnectivityManager) ctx
				.getSystemService(Context.CONNECTIVITY_SERVICE);

		if (connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnected()
				|| connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE)
						.isConnected()) {
			return true;
		}

		return false;
	}

	/**
	 * Get width of screen device (px)
	 * 
	 * @param context
	 *            The calling context.
	 * @return width of screen
	 */
	public static int getWidthOfScreen(Context context) {
		DisplayMetrics metrics = new DisplayMetrics();
		((Activity) context).getWindowManager().getDefaultDisplay()
				.getMetrics(metrics);
		int widthPixels = metrics.widthPixels;
		return widthPixels;
	}

	/**
	 * Get height of screen device (px)
	 * 
	 * @param context
	 *            The calling context.
	 * @return height of screen
	 */
	public static int getHeightOfScreen(Context context) {
		DisplayMetrics metrics = new DisplayMetrics();
		((Activity) context).getWindowManager().getDefaultDisplay()
				.getMetrics(metrics);
		int heightPixels = metrics.heightPixels;
		return heightPixels;
	}

	/**
	 * Hide keyboard
	 * 
	 * @param activity
	 *            The calling activity.
	 */
	public static void hideSoftKeyboard(Activity activity) {
		InputMethodManager inputMethodManager = (InputMethodManager) activity
				.getSystemService(Activity.INPUT_METHOD_SERVICE);
		inputMethodManager.hideSoftInputFromWindow(activity.getCurrentFocus()
				.getWindowToken(), 0);
	}

	/**
	 * Hide keyboard
	 * 
	 * @param activity
	 *            The calling activity.
	 */
	public static void hideSoftKeyboard(Activity activity, View v) {
		InputMethodManager inputMethodManager = (InputMethodManager) activity
				.getSystemService(Activity.INPUT_METHOD_SERVICE);
		inputMethodManager.hideSoftInputFromWindow(v.getWindowToken(), 0);

	}

	/**
	 * Show keyboard
	 * 
	 * @param activity
	 *            The calling activity.
	 */
	public static void showSoftKeyboard(Activity activity) {
		InputMethodManager imm = (InputMethodManager) activity
				.getSystemService(Activity.INPUT_METHOD_SERVICE);
		imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, 0);
	}

	/**
	 * Show keyboard
	 * 
	 * @param activity
	 *            The calling activity.
	 */
	public static void showSoftKeyboard(Activity activity, View v) {
		InputMethodManager inputMethodManager = (InputMethodManager) activity
				.getSystemService(Activity.INPUT_METHOD_SERVICE);
		inputMethodManager.showSoftInputFromInputMethod(v.getWindowToken(), 0);
	}

	// check email valid
	public static boolean isEmailValid(String email) {
		boolean isValid = false;

		String expression = "^[\\w\\.-]+@([\\w\\-]+\\.)+[A-Z]{2,4}$";
		CharSequence inputStr = email;

		Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE);
		Matcher matcher = pattern.matcher(inputStr);
		if (matcher.matches()) {
			isValid = true;
		}
		return isValid;
	}

	// get email in device
	public static String getEmailInDevice(Context context) {
		String possibleEmail = "";
		Pattern emailPattern = Patterns.EMAIL_ADDRESS; // API level 8+
		Account[] accounts = AccountManager.get(context).getAccounts();
		for (Account account : accounts) {
			if (emailPattern.matcher(account.name).matches()) {
				possibleEmail = account.name;
				break;
			}

		}

		return possibleEmail;
	}

	// check string in json array
	public static boolean isExistsInArray(JSONArray jsonArray, String key) {
		return jsonArray.toString().contains(key);
	}
	
	public static int GetDipsFromPixel(Context context, float pixels)
    {
     // Get the screen's density scale
     final float scale = ((Activity) context).getResources().getDisplayMetrics().density;
     // Convert the dps to pixels, based on density scale
     return (int) (pixels * scale + 0.5f);
    }
	

	public static Animation isFromRightAnimation(int duration) {
		Animation inFromRight = new TranslateAnimation(
				Animation.RELATIVE_TO_PARENT, +1.0f,
				Animation.RELATIVE_TO_PARENT, 0.0f,
				Animation.RELATIVE_TO_PARENT, 0.0f,
				Animation.RELATIVE_TO_PARENT, 0.0f);
		inFromRight.setDuration(duration);
		inFromRight.setFillAfter(true);
		inFromRight.setFillEnabled(true);
		inFromRight.setInterpolator(new AccelerateInterpolator());
		return inFromRight;
	}

	public static Animation outToLeftAnimation(int duration) {
		Animation outtoLeft = new TranslateAnimation(
				Animation.RELATIVE_TO_PARENT, 0.0f,
				Animation.RELATIVE_TO_PARENT, -1.0f,
				Animation.RELATIVE_TO_PARENT, 0.0f,
				Animation.RELATIVE_TO_PARENT, 0.0f);
		outtoLeft.setDuration(duration);
		outtoLeft.setFillAfter(true);
		outtoLeft.setFillEnabled(true);
		outtoLeft.setInterpolator(new AccelerateInterpolator());
		return outtoLeft;
	}

	public static Animation inFromLeftAnimation(int duration) {
		Animation inFromLeft = new TranslateAnimation(
				Animation.RELATIVE_TO_PARENT, -1.0f,
				Animation.RELATIVE_TO_PARENT, 0.0f,
				Animation.RELATIVE_TO_PARENT, 0.0f,
				Animation.RELATIVE_TO_PARENT, 0.0f);
		inFromLeft.setDuration(duration);
		inFromLeft.setFillAfter(true);
		inFromLeft.setFillEnabled(true);
		inFromLeft.setInterpolator(new AccelerateInterpolator());
		return inFromLeft;

	}

	public static Animation outToRightAnimation(int duration) {
		Animation outtoRight = new TranslateAnimation(
				Animation.RELATIVE_TO_PARENT, 0.0f,
				Animation.RELATIVE_TO_PARENT, +1.0f,
				Animation.RELATIVE_TO_PARENT, 0.0f,
				Animation.RELATIVE_TO_PARENT, 0.0f);
		outtoRight.setDuration(duration);
		outtoRight.setFillAfter(true);
		outtoRight.setFillEnabled(true);
		outtoRight.setInterpolator(new AccelerateInterpolator());
		return outtoRight;

	}
}
